import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado.websocket import WebSocketClosedError, WebSocketHandler

# WebSocket 处理器
class WebSocketHandler(WebSocketHandler):
    def initialize(self):
        # 获取客户端IP地址并保存
        self.client_ip = self.request.remote_ip
    def open(self):
        print("WebSocket连接已建立")


    def on_message(self, message):
        print("收到来自WebSocket的消息:", message)
        # 回复消息
        self.write_message(f"收到你的消息{self.client_ip}: " + message)

    def on_close(self):
        print("WebSocket连接已关闭")

def make_app():
    return tornado.web.Application([
        (r"/", WebSocketHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    print("Tornado WebSocket服务器已启动")
    tornado.ioloop.IOLoop.current().start()
